import type { EChartsOption } from "echarts"
import type React from "react"
import { useEffect, useRef } from "react"
import type { EchartsInnerProp } from "../../views/NewHome/types"
import * as echarts from "echarts"
import type { XAXisOption } from "echarts/types/dist/shared"

// echarts的配置数据
const axiosOption: EChartsOption = {
  // 图例文字颜色
  textStyle: {
    color: "#333"
  },

  // 提示框
  tooltip: {
    trigger: "axis"
  },

  xAxis: {
    type: "category", // 类目轴
    data: [],
    axisLine: {
      lineStyle: {
        color: "#17b3a3"
      }
    },
    axisLabel: {
      interval: 0,
      color: "#333333"
    }
  },

  yAxis: [
    {
      type: "value",
      axisLine: {
        lineStyle: {
          color: "#17b3a3"
        }
      }
    }
  ],

  color: ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980", "#d87a80", "#8d98b3"],

  series: [],
}

const normalOption: EChartsOption = {
  tooltip: {
    trigger: "item",
  },

  color: [
    "#0f78f4",
    "#dd536b",
    "#9462e5",
    "#a6a6a6",
    "#e1bb22",
    "#39c362",
    "#3ed1cf",
  ],

  series: [],
}


const Echarts = ({ style, chartData, isAxisChart = true }: { style: React.CSSProperties, chartData: EchartsInnerProp, isAxisChart?: boolean }) => {
  // 获取dom实例
  const echartRef = useRef<HTMLDivElement | null>(null)
  const echartObj = useRef<echarts.EChartsType | null>(null)

  useEffect(() => {
    let options

    // echarts的初始化
    echartObj.current = echarts.init(echartRef.current)

    // 设置option
    if (isAxisChart) {
      // 设置option
      axiosOption.xAxis.data = chartData.xData
      axiosOption.series = chartData.series
      options = axiosOption
    } else {
      normalOption.series = chartData.series
      options = normalOption
    }

    // 使用新的 options 更新 echarts 实例
    echartObj.current.setOption(options);
  }, [chartData, isAxisChart])

  return (
    <div style={style} ref={echartRef}></div>
  )
}

export default Echarts
